package com.hsf.cloudweb.service.impl;


import com.hsf.cloudweb.model.UserInfo;
import com.hsf.cloudweb.repository.UserRepository;
import com.hsf.cloudweb.service.IUserService;
import com.hsf.cloudweb.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserRepository userDao;
    @Value("${password.key}")
    private String key;
    @Override
    public UserInfo saveUser(UserInfo userInfo) {
        try {
            String password= MD5Util.md5(userInfo.getPassword(),key);
            userInfo.setPassword(password);
        } catch (Exception ex) {
           throw new RuntimeException(ex);
        }
        return userDao.save(userInfo);
    }

    @Override
    public UserInfo findUserByUserAccount(String userAccount) {

        return userDao.findByUserAccount(userAccount);
    }

    @Override
    public boolean login(String userAccount, String password) {
        UserInfo userInfo = userDao.findByUserAccount(userAccount);
        if(userInfo==null){
            return false;
        }
        try {
            return  MD5Util.verify(password,key,userInfo.getPassword());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    @Override
    @Transactional
    public void modifyPassword(String userAccount, String password) {
        try {
            String passwordText = MD5Util.md5(password,key);
            userDao.modifyPassword(userAccount,passwordText);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }
}
